package com.fjh.common.handler;

import com.fjh.common.CodeMsg;
import com.fjh.common.Result;
import com.fjh.common.exces.BusinessException;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局的异常处理器
 * 拦截从Controller 里面来的异常
 * 要让它生效,必须创建该对象才行
 * 我们需要在spring-mvc.xml 文件里面添加包扫描
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理Shiro的登录异常
     */
    @ExceptionHandler(value = ShiroException.class)
    public Result loginException(ShiroException shiroException) {
//        // 1 没有该用户
//        if (shiroException instanceof UnknownAccountException) {
//            return Result.fail(400, "没有该用户");
//        }
//        // 2 用户的密码错误
//        if (shiroException instanceof IncorrectCredentialsException) {
//            return Result.fail(400, "密码错误");
//        }
//        // 3 没有权限
//        if (shiroException instanceof UnauthenticatedException) {
//            return Result.fail(400, "没有权限访问");
//        }
        if (shiroException instanceof UnauthorizedException) {
            return Result.fail(400, "没有权限访问");
        }
        // 4 登录的错误/提示: 能模糊就模糊
        if (shiroException instanceof AuthenticationException) {
            return Result.fail(CodeMsg.USER_USER_PASSWORD_ERROR.code, CodeMsg.USER_USER_PASSWORD_ERROR.msg);
        }
        return Result.fail();
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result handlerIllegalArgumentException(IllegalArgumentException exception){
        String message = exception.getMessage();
        System.out.println(message);
        return Result.fail(400,message);
    }

    /**
     * 处理自己定义的异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public Result handlerBusinessException(BusinessException exception) {
        Integer num = exception.getNum();
        String message = exception.getMessage();
        return Result.fail(num, message);
    }
}
